#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdarg.h>
#include "error.h"
#include "log.h"

// 全局变量
static char g_last_error_message[512] = {0};
static pthread_mutex_t g_error_mutex = PTHREAD_MUTEX_INITIALIZER;

// 错误码到描述的映射表
static const struct {
    int error_code;
    const char *description;
} error_descriptions[] = {
    {ERROR_SUCCESS, "成功"},
    {ERROR_GENERAL, "一般错误"},
    {ERROR_MEMORY, "内存分配错误"},
    {ERROR_PARAMETER, "参数错误"},
    {ERROR_FILE, "文件操作错误"},
    {ERROR_DEVICE, "设备错误"},
    {ERROR_TIMEOUT, "超时错误"},
    {ERROR_NOT_SUPPORTED, "不支持的操作"},
    {ERROR_BUSY, "资源忙"},
    {ERROR_NOT_FOUND, "资源未找到"},
    {ERROR_ALREADY_EXISTS, "资源已存在"},
    {ERROR_PERMISSION, "权限错误"},
    {ERROR_CONNECTION, "连接错误"},
    {ERROR_PROTOCOL, "协议错误"},
    {ERROR_CANCELLED, "操作被取消"},
    {0, NULL} // 结束标记
};

const char *error_string(int error_code)
{
    // 查找错误码对应的描述
    for (int i = 0; error_descriptions[i].description != NULL; i++) {
        if (error_descriptions[i].error_code == error_code) {
            return error_descriptions[i].description;
        }
    }
    
    // 如果没有找到，返回通用描述
    static char unknown_error[64];
    snprintf(unknown_error, sizeof(unknown_error), "未知错误码: %d", error_code);
    return unknown_error;
}

void error_set_message(const char *format, ...)
{
    if (!format) {
        return;
    }
    
    pthread_mutex_lock(&g_error_mutex);
    
    va_list args;
    va_start(args, format);
    vsnprintf(g_last_error_message, sizeof(g_last_error_message), format, args);
    va_end(args);
    
    pthread_mutex_unlock(&g_error_mutex);
}

const char *error_get_message(void)
{
    pthread_mutex_lock(&g_error_mutex);
    const char *message = g_last_error_message[0] ? g_last_error_message : "无详细信息";
    
    // 创建一个临时副本返回，避免加锁期间被修改
    static char message_copy[512];
    strncpy(message_copy, message, sizeof(message_copy) - 1);
    
    pthread_mutex_unlock(&g_error_mutex);
    return message_copy;
}

void error_clear_message(void)
{
    pthread_mutex_lock(&g_error_mutex);
    g_last_error_message[0] = '\0';
    pthread_mutex_unlock(&g_error_mutex);
}

void error_print(const char *file, int line, const char *func, int error_code)
{
    const char *error_desc = error_string(error_code);
    const char *custom_message = error_get_message();
    
    // 使用日志系统输出错误信息
    LOG_ERROR("[%s:%d %s()] 错误码: %d, 描述: %s, %s", 
              file, line, func, error_code, error_desc, custom_message);
    
    // 清除自定义错误消息
    error_clear_message();
}